package algorithm.sort;

public class ArraysSort {

    public static void main(String[] args) {
        int[] a = {1, 3, 5, 70};
        int[] b = {20, 40, 60, 80};
        sort(a , b ,4);
    }

    //给定两个排好序的数组
    private static int sort(int[] a , int[] b , int k){
        if( a.length + b.length < k ){
            return -1;
        }
        // 返回两个数组第K小的值
        int aIndex = 0 , bIndex = 0;//两个指针初始分别指向A和B的头
        while (true){
            if (aIndex < a.length){
                while (bIndex == b.length || a[aIndex] <= b[bIndex]) {
                    aIndex ++;
                    if( aIndex + bIndex == k ){
                        return a[aIndex];
                    }
                }
            }
            if ( bIndex < b.length ){
                while ( aIndex == a.length || a[aIndex] >= b[bIndex] ){
                    bIndex ++;
                }
                if( aIndex + bIndex == k ){
                    return b[bIndex];
                }
            }
        }
    }
}
